package com.niit.broadcastreciver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    MyBroadcastReceiver myBroadcastReceiver;
    String Tag = "com.niit.broadcastReceiver";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button registerBtn = findViewById(R.id.register);
        Button sendBtn = findViewById(R.id.send);
        Button unregisterBtn = findViewById(R.id.unregister);

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBroadcastReceiver = new MyBroadcastReceiver();
                IntentFilter filter = new IntentFilter();
                filter.addAction(Tag);
                registerReceiver(myBroadcastReceiver,filter);
            }
        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("info","这是一条广播");
                intent.setAction(Tag);
                sendBroadcast(intent);
            }
        });

        unregisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    unregisterReceiver(myBroadcastReceiver);
                }catch (IllegalArgumentException e){
                    if (e.getMessage().contains("Receiver not registered")){
                        Toast.makeText(MainActivity.this,"请先点击注册广播接收器",Toast.LENGTH_LONG).show();
                        }
                    else{
                        throw e;
                    }
                }
            }
        });
    }

    public class MyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent){
            Toast.makeText(context,"您收到的广播为："+intent.getStringExtra("info"),Toast.LENGTH_LONG).show();
        }
    }
}
